import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);
import apiUrl from '@/common/apiUrl';
import myMixin from '@/common/myMixin.js';

const store = new Vuex.Store({
  state: {
    // 登录信息
    memberInfo: {},
    // 使用的地址
    activeAddress: null,
    // 系统设置
    systemInfo: {},
    // 国家区号
    countryCode: [],
    // 平台
    clientplatform: uni.getSystemInfoSync().platform,
    // 当前时间
    systemNow: new Date().getTime(),
  },
  mutations: {
    //save member information
    saveMember(state, obj) {
      const storageMember = uni.getStorageSync('member') || {};
      const memberInfo = { ...storageMember, ...obj };
      uni.setStorageSync('member', memberInfo);
      state.memberInfo = memberInfo;
    },
    // save member from storage
    saveStorageMember(state) {
      uni.getStorage({
        key: 'member',
        success: (e) => {
          state.memberInfo = e.data;
          // this.dispatch('getMemberInfo');
        },
      });
    },
    clearMember(state) {
      uni.removeStorageSync('member');
      uni.removeStorage({ key: 'memberSecretV2' });
      state.memberInfo = {};
    },
    saveSystemInfo(state, obj) {
      state.systemInfo = obj;
    },
    setCountryCode(state, arr) {
      state.countryCode = arr;
    },
    setSystemNow(state, now) {
      if (now) state.systemNow = now;
    },
    // save address
    setActiveAddress(state, data) {
      state.activeAddress = data;
    },
    delAddress(state) {
      state.activeAddress = null;
      uni.removeStorage({ key: 'activeAddress' });
    },
    // 退出登录
    logout() {
      this.commit('clearMember');
      this.commit('delAddress');
      uni.showTabBar();
    },

  },
  actions: {
    //地址
    async getAddressInfo({ commit }) {
      return apiUrl.getAddressList().then((res) => {
        if (res.data.code == 0) {
          let arr = res.data.data;
          let o = null;
          if (arr.length) o = arr.find((v) => v.isDefault) || arr[0];
          commit('setActiveAddress', o);
        }
      });
    },
    //系统设置
    async getSystemInfo() {

      // 虚拟数据 start
      return new Promise((resolve, reject) => {resolve()});
      // 虚拟数据 end

      return new Promise((resolve, reject) => {
        apiUrl
          .getsystemInfo({
            data: {
              incType: 'integral_replace_page',
            },
          })
          .then((res) => {
            if (res.data.code == 0) {
              res.data.data.now = res.data.now;
              this.commit('saveSystemInfo', res.data.data);
              resolve();
            } else {
              reject();
            }
          });
      });
    },
    //会员信息
    async getMemberInfo({ commit, state }, params = {}) {
      if (state.memberInfo) {
        // if (state.memberInfo.isAnonymous) {
        //   return Promise.resolve();
        // }
        // console.log('已登录')
        //已经登陆过
        return apiUrl
          .getMemberInfo(
            {
              data: {
                id: state.memberInfo.id,
                ...params,
              },
            }
          )
          .then((res) => {
            let { code, msg:message='' } = res.data;
            if (code == 0) {
              commit('saveMember', res.data.data);
              return;
            } else {
              if (code == 1001) message = '缺少传入参数';
              if (code == 1002) message = '序列号无效';
              if (code == 1003) message = '当前状态不允许修改报修单';
              if (code == 1004) message = '手机号未授权';
              if (code == 1005) message = '非法访问';
              if (code == 555 || code == 403) return;
              uni.showToast({
                icon: 'none',
                duration: 2000,
                title: message,
                mask: true,
              });
              const pages = getCurrentPages();
              const currentPage = pages[pages.length - 1];
              if (currentPage) uni.setStorageSync('pagefromDetail', true);
              // setTimeout(() => {
              //   commit('logout');
              //   uni.navigateTo({
              //     url: '/pages/login/login',
              //   });
              // }, 2000);
            }

          });
      } else {
        //未登录过
        // console.log('未登录')
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        if (currentPage) uni.setStorageSync('pagefromDetail', true);
        // uni.navigateTo({
        //   url: '/pages/login/login',
        // });
      }
    },
    //国家编号
    async getCountryList({ commit }) {
      apiUrl.tabGetCountryList().then((res) => {
        if (res.data.code == 0) {
          commit('setCountryCode', res.data.data);
        }
      });
    },
    //获取富文本
    async api_ui_getfulltxt({ commit },params={}) {
      return new Promise((resolve,reject) => {
        apiUrl.api_ui_getfulltxt(
          {
          ...params,
          }
        ).then((res) => {
          const { code,msg:message='', data } = res.data
          if (code == 0) {
            if(data&&data.content){
              data.content =  this.filterSpecialSymbol(data.content)
              resolve(data.content)
            }
          }else {
            uni.showToast({
              duration: 1500,
              title: message
            })
            reject()
          }
        });
      });
    },
    // 1.微信登录
    async api_wx_getopenidbycode({ commit, state }, params={}) {
      const vm = this
      uni.showLoading({
        title: '加载中...'
      })
      return new Promise((resolve) => {
        apiUrl
          .api_wx_getopenidbycode({
            data: {
              code: params.code,
            },
          })
          .then((res) => {
            uni.hideLoading()
            const { code,msg:message='', data } = res.data;

            if (code == 0) {
              if (data) {
                resolve(data);
              }
            }else {
              uni.showToast({
                icon: 'error',
                duration: 1500,
                title: message
              })
              resolve();
            }
          });
      });
    },
    // 2.获取用户手机号
    async api_wx_getmobbyauth({ commit, state }, params={}) {
      const vm = this
      uni.showLoading({
        title: '加载中...'
      })
      return new Promise((resolve) => {
        apiUrl
          .api_wx_getmobbyauth({
            data: {
              code: params.code,
              openid: params.openid,
            },
          })
          .then((res) => {
            uni.hideLoading()
            const { code,msg:message='', data } = res.data;

            if (code == 0) {
              if (data) {
                const { mob, hasmob=1 } = data
                let memberInfo = {
                  openid: params.openid,
                  code: params.code,
                  mob: mob,
                  hasmob: hasmob
                }
                commit('saveMember',memberInfo)
                resolve(data);
              }
            }else {
              uni.showToast({
                icon: 'error',
                duration: 1500,
                title: message
              })
              resolve();
            }
          });
      });
    },
    // 检测是否登录
    async check_wx_login({ commit, state }, params = {}) {
      const vm = this
      return new Promise((resolve,reject) => {
        if (myMixin&&myMixin.methods&&!myMixin.methods.isObjectEmptyOrUndefined(state.memberInfo)) {
          console.log('已登录')
          // console.log('state.memberInfo',state.memberInfo)
          const { hasmob, openid } = state.memberInfo
          if(hasmob == 0 && params&&params.isSubmit){
            vm.dispatch('api_wx_getmobbyauth',{
              openid: openid,
              code: params.code,
            })
          }
        } else {
          //未登录过
          // console.log('未登录')
          // 登录
          uni.login({
            provider: 'weixin', //使用微信登录
            onlyAuthorize: true, // 微信登录仅请求授权认证
            success: function(e) {
              console.log('uni.login',e);
              const {code} = e
              if (code) {
                vm.dispatch('api_wx_getopenidbycode',{
                  code: code,
                }).then((res)=>{
                  uni.hideLoading()
                  if(res){
                    const { openid, hasmob } = res
                    commit('saveMember',{
                      openid: openid,
                      id: code,
                      hasmob: hasmob
                    })
                  }
                  resolve(res);
                })
              } else {
                commit('clearMember')
                uni.showToast({
                  icon: 'none',
                  title: 'uni.login API 获取code失败'
                })
                reject()
                return false;
              }
            },
            fail: function(err) {
              console.log('err', err);
              const { errMsg } = err
              if(errMsg){
                uni.showToast({
                  icon: 'error',
                  duration: 1500,
                  title: errMsg
                })
              }
              reject()
            }
          })
        }
      })
    },

  },
  getters: {

  },
});

export default store;
